package app.auto.designer;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import app.auto.designer.intfs.SetIntfsActivity;
import app.auto.designer.memcache.GlobalCache;
import app.auto.designer.tool.BackTwiceExitActivity;
import app.auto.designer.view.ViewActivity;
import app.auto.runner.base.RRes;
import app.auto.runner.base.SPrefUtil;
import app.auto.runner.base.action.ViewInflater;


public class ModelDesignActivity extends BackTwiceExitActivity {
    private GestureDetector mGestureDetector;
    private DrawerLayout mDrawerLayout;
    private String SPNAME = "frame";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auto_action_ui);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.mipmap.ic_launcher, R.string.app_name, R.string.app_name) {

            /**
             * Called when a drawer has settled in a completely closed state.
             */

            public void onDrawerClosed(View view) {
//                getActionBar().setTitle(mTitle);
            }

            /**
             * Called when a drawer has settled in a completely open state.
             */
            public void onDrawerOpened(View drawerView) {
//                getActionBar().setTitle(mDrawerTitle);
            }
        };

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        mDrawerLayout.findViewById(R.id.iv_back).setVisibility(View.INVISIBLE);
        ((TextView) mDrawerLayout.findViewById(R.id.ivLeft)).setText("三");
        ((TextView) mDrawerLayout.findViewById(R.id.ivLeft)).setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
        ((TextView) mDrawerLayout.findViewById(R.id.ivLeft)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawerLayout.openDrawer(Gravity.LEFT);
            }
        });


        View nav = findViewById(R.id.nav);
//        MapViewConf.with(getBaseContext()).conf(MapViewConf.with(getBaseContext()).source(R.layout.auto_string_item)).source(getListRes(), findViewById(R.id.left_drawer)).toView();
        nav.findViewById(R.id.ivLeft).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        nav.findViewById(R.id.iv_back).setVisibility(View.GONE);
        ((TextView) nav.findViewById(R.id.ivRight_text)).setText("保存");
        nav.findViewById(R.id.ivRight_text).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View
                                        v) {

                finish();
            }
        });


        //        String name = (String) SPrefUtil.getValue(SPNAME, "left_drawer", String.class);
        String name = getIntent().getStringExtra("layout");

        if (!TextUtils.isEmpty(name)) {
            ledView_to_set(name);
            setHasIdViewWhiteFrame(userview);
        }
        JSONObject jsonObject = initSideListView(userview);
        GlobalCache.getInstance().addEditLayout(name, true);

        //do mark for previous ui

        findViewById(R.id.down).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(v.getContext(), SetIntfsActivity.class));
            }
        });
        findViewById(R.id.up).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    private JSONObject initSideListView(View userview) {
        JSONObject jobject = new JSONObject();
        try {

            jobject.put("widget", userview.getClass().getName().replaceAll("com.zhy.autolayout.Auto", "").replaceAll("android.widget.", "").replaceAll("android.view.", ""));
            if (userview instanceof ViewGroup) {
                JSONArray array = new JSONArray();
                if (((ViewGroup) userview).getChildCount() > 0) {
                    for (int i = 0; i < ((ViewGroup) userview).getChildCount(); i++) {
                        View view = ((ViewGroup) userview).getChildAt(i);
                        array.put(initSideListView(view));
                    }
                }
                jobject.put("views", array);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jobject;
    }

    View userview;

    private void ledView_to_set(String name) {
        mDrawerLayout.closeDrawer(Gravity.LEFT);
        int layoutid = RRes.get("R.layout." + name + "").getAndroidValue();
        SPrefUtil.putValue(getBaseContext(), SPNAME, "left_drawer", name);
        ((ViewGroup) findViewById(R.id.content)).removeAllViews();
        userview = new ViewInflater(ModelDesignActivity.this).inflate(layoutid, null);
        ((ViewGroup) findViewById(R.id.content)).addView(userview);

    }

    public void closeDrawer(int id) {
        mDrawerLayout.closeDrawer(Gravity.LEFT);
        findViewById(id).performClick();
    }

    List<View> views = new ArrayList<View>();

    //设置有id的控件 带白框
    @SuppressLint("NewApi")
    private void setHasIdViewWhiteFrame(View userview) {
        if (userview.getId() != 0) {
            views.add(userview);
            userview.setForeground(ContextCompat.getDrawable(getBaseContext(),R.drawable.auto_background_rect_white));
            setViewClickPanel(userview);
        }
        if (userview instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) userview).getChildCount(); i++) {
                View view = ((ViewGroup) userview).getChildAt(i);

                setHasIdViewWhiteFrame(view);
            }

        }
    }

    private void setViewClickPanel(View userview) {
        if (userview instanceof AdapterView) {

        } else {
            userview.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String value = "";
                    if (v instanceof TextView) {
                        value = ((TextView) v).getText().toString();
                    } else if (v instanceof app.auto.runner.base.widget.ImageView) {
                        value = ((app.auto.runner.base.widget.ImageView) v).getUrl();
                    }
                    String id = RRes.getAttrValue_itsname().get(v.getId());

                    startActivity(new Intent(v.getContext(), ViewActivity.class).putExtra("value", value).putExtra("idname", id).putExtra("type", v.getClass().getSimpleName()).putExtra("W x H", v.getWidth() + " x " + v.getHeight()));
                }
            });
        }
    }

    public List getListRes() {
        RRes.TypeAttrs clz = RRes.getResType().get("layout");
        List list = new ArrayList<String>(clz.attrMaps.keySet());
        return list;

    }


    private class simpleGestureListener extends
            GestureDetector.SimpleOnGestureListener {

        /*****
         * OnGestureListener的函数
         *****/

        final int FLING_MIN_DISTANCE = 100, FLING_MIN_VELOCITY = 200;

        // 触发条件 ：
        // X轴的坐标位移大于FLING_MIN_DISTANCE，且移动速度大于FLING_MIN_VELOCITY个像素/秒

        // 参数解释：
        // e1：第1个ACTION_DOWN MotionEvent
        // e2：最后一个ACTION_MOVE MotionEvent
        // velocityX：X轴上的移动速度，像素/秒
        // velocityY：Y轴上的移动速度，像素/秒
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                               float velocityY) {


            if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
                    && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
                // Fling left
//                Log.i("MyGesture", "Fling left");
                mDrawerLayout.closeDrawer(Gravity.LEFT);
//                Toast.makeText(ModelDesignActivity.this, "Fling Left", Toast.LENGTH_SHORT).show();
            } else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
                    && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
                // Fling right
//                Log.i("MyGesture", "Fling right");
                mDrawerLayout.openDrawer(Gravity.LEFT);
//                Toast.makeText(ModelDesignActivity.this, "Fling Right", Toast.LENGTH_SHORT).show();
            }
            return true;
        }

    }
}
